package br.com.massai.model.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

import br.com.massai.model.entity.Entry;
import br.com.massai.model.entity.Spreadsheet;
import br.com.massai.model.exceptions.ErrorCore;
import br.com.massai.model.exceptions.SystemException;
import br.com.massai.view.enums.Flow;
import br.com.massai.view.enums.TypePayroll;

@Stateless
public class EntryDAO extends GenericDAO<Entry> implements EntryRepository {

	private static final long serialVersionUID = -8345363005938717114L;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Entry> getEntriesBySpreadsheet(Spreadsheet spreadsheet) throws SystemException {
		try {
			return em.createQuery("SELECT e FROM Entry e WHERE e.spreadsheet =:spreadsheet").setParameter("spreadsheet", spreadsheet).getResultList();

		} catch (SystemException e) {
			throw new SystemException(ErrorCore.ERROR_LOADING_ENTRY);
		}
	}
	
	@Override
	public Entry getEntryForImportation(String empCodigo, String epgCodigo, String accrualBasis, TypePayroll typePayroll) throws SystemException {
		try {
			Entry entry = null;
			if(epgCodigo != null && !epgCodigo.isEmpty() && accrualBasis != null && !accrualBasis.isEmpty() && typePayroll != null){
				Query query = super.em.createQuery(	"SELECT e FROM Entry e " +
													"WHERE e.employee.epgCodigo =:epgCodigo " +
													"AND e.employee.empCodigo =:empCodigo " +
													"AND e.spreadsheet.accrualBasis =:accrualBasis " +
													"AND e.spreadsheet.typePayroll =:typePayroll " +
													"AND e.spreadsheet.flow =:flow")
													.setParameter("epgCodigo", epgCodigo)
													.setParameter("empCodigo", empCodigo)
													.setParameter("accrualBasis", accrualBasis)
													.setParameter("typePayroll", typePayroll)
													.setParameter("flow", Flow.APROVED);
				entry = (Entry) query.getSingleResult();
				System.out.println("########## " + entry);
			}
			return entry;

		} catch (NoResultException e) {
			return null;
		} catch (NonUniqueResultException e) {
			return null;
//			throw new SystemException(ErrorCore.ERROR_NON_UNIQUE_RESULT, e);
		}
	}
}